import 'package:casdon/common/service/at_auth_service.dart';

import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/modules/home/application/notification/tuya_auth_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_notifier.dart';
import 'package:casdon/modules/login/data/api/login_api.dart';
import 'package:casdon/modules/login/domain/states/login_oneTap_state.dart';
import 'package:casdon/modules/login/domain/usecases/login_usecase.dart';
import 'package:casdon/modules/login/providers/login_provider.dart';

class LoginOnetapNotifier extends LoginNotifier<LoginOnetapState> {
  bool _isLoginInProgress = false;
  String? _consumedToken;
  static String? _lastProcessedToken;
  bool _isRequestingToken = false;

  void login() {
    if (_isRequestingToken) {
      Log.i("一键登录取号中，忽略重复请求");
      return;
    }
    _isRequestingToken = true;
    try {
      AtAuthService().getLoginToken(
        onEvent: (event) {
          if (event["resultCode"] == "600000") {
            Log.i(event);
            // 调用ciot云登录
            final token = event["token"] as String?;
            if (token != null && token == _consumedToken) {
              Log.i("一键登录 token 已使用过，忽略重复触发");
              return;
            }
            _login(token);
          }
          _isRequestingToken = false;
        },
      );
    } catch (e) {
      Log.e("一键登录启动失败", e, StackTrace.current);
      _isRequestingToken = false;
    }
  }

  @override
  LoginOnetapState build() {
    ref.keepAlive();
    ref.onDispose(() {
      Log.i("119615 LoginOnetapNotifier 已销毁");
      AtAuthService().dispose();
    });
    return LoginOnetapState.initial();
  }

  void _login(String? token) async {
    if (token != null && token == _lastProcessedToken) {
      Log.i("一键登录 token 已处理，忽略重复触发");
      return;
    }
    Log.i("119615 一键登录触发 $_isLoginInProgress");
    if (_isLoginInProgress) {
      Log.i("一键登录进行中，忽略重复触发");
      return;
    }
    if (token == null) {
      _isRequestingToken = false;
      setFailure(msg: "一键登录失败，请稍后再试！");
      return;
    }
    _isLoginInProgress = true;
    _consumedToken = token;
    _lastProcessedToken = token;
    state = LoginOnetapState.initial();
    setLoading();
    try {
      LoginUsecase loginUsecase = ref.read(loginUsecaseProvider);
      Log.i("119615 一键登录，登录$token");
      RequestLogin request = RequestLogin(
        grantType: LoginGrantType.phone.name,
        token: token,
      );
      final ret = await loginUsecase.execute(request);

      final authStorage = ref.read(authStorageProvider.notifier);
      await authStorage.saveToken(ret.access_token);
      await ref.read(tuyaLoginProvider.notifier).login();
      final tuyaSuccess = ref.read(tuyaLoginStateProvider);
      if (!tuyaSuccess) {
        setFailure(msg: "一键登录失败，请稍后再试！");
        return;
      }
      setSuccess("一键登录成功");
    } on BusinessException catch (e) {
      setFailure(errorCode: e.code, msg: e.msg);
    } catch (e) {
      setFailure(msg: "一键登录失败，请稍后再试！");
    } finally {
      _isRequestingToken = false;
      _isLoginInProgress = false;
      Log.i("119615 一键登录触发finally $_isLoginInProgress");
    }
  }
}
